///  description: 基于微信UI的图片/视频选择器(支持拍照及录制视频) 封装wechat_assets_picker、wechat_camera_picker

import 'package:common/image/image_tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reorderable_grid_view/widgets/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

/// description
typedef AssetEntityListBlock = void Function(List<AssetEntity> assetEntityList);
typedef AssetEntityBlock = void Function(AssetEntity? assetEntity);

class PickerImageDragWidget extends StatefulWidget {
  const PickerImageDragWidget({
    Key? key,
    this.maxAssets = 9,
    this.lineCount = 4,
    this.itemSpace = 5.0,
    this.bgColor = Colors.transparent,
    this.callBack,
    this.videoCallback,
  }) : super(key: key);

  final int maxAssets; // 最大数量
  final int lineCount; // 一行显示几个
  final double itemSpace; // 每个GridView item间距(GridView四周与内部item间距在此统一设置)
  final Color bgColor; // 背景色
  final AssetEntityListBlock? callBack; // 选择回调
  final AssetEntityBlock? videoCallback;
  @override
  State<PickerImageDragWidget> createState() => PickerImageDragWidgetState();
}

class PickerImageDragWidgetState extends State<PickerImageDragWidget> {
  List<AssetEntity> _selectedAssets = [];
  final _gridViewKey = GlobalKey();
  final _scrollController = ScrollController();

  List<int> lockedIndices = <int>[];

  static GlobalKey tabKey = GlobalKey();

  ///获取state供外部使用
  static PickerImageDragWidgetState? currentInstance() {
    var state = PickerImageDragWidgetState.tabKey.currentContext?.findAncestorStateOfType<PickerImageDragWidgetState>();
    return state;
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    int count = _selectedAssets.length + 1;
    num coul = count % widget.lineCount == 0 ? 0 : 1 + count / widget.lineCount;
    if (count < 5) {
      coul = 1;
    } else if (count > 4 && count < 8) {
      coul = 2;
    } else if (count > 8) {
      coul = 3;
    }
    double itemWidth = (Get.width - 10 * (widget.lineCount - 1) - 10 * (widget.lineCount - 1)) / widget.lineCount;
    return SizedBox(
      key: tabKey,
      height: coul * itemWidth.h + coul * 10.h,
      child: imageDragGridWarpper(),
    );
  }

  Widget videoWarpper(double itemWidth) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
            alignment: Alignment.topLeft,
            width: itemWidth,
            height: itemWidth,
            // color: Colors.white,
            child: _selectedAssets.isNotEmpty ? _itemWidget(0) : _addBtnWidget()),
      ],
    );
  }

  Widget imageDragGridWarpper() {
    lockedIndices = <int>[_selectedAssets.length];
    return ReorderableBuilder.builder(
      key: Key(_gridViewKey.toString()),
      onReorder: _handleReorder,
      lockedIndices: lockedIndices,
      nonDraggableIndices: lockedIndices,
      onDragStarted: _handleDragStarted,
      onUpdatedDraggedChild: _handleUpdatedDraggedChild,
      onDragEnd: _handleDragEnd,
      scrollController: _scrollController,
      childBuilder: (itemBuilder) {
        return GridView.builder(
          key: _gridViewKey,
          controller: _scrollController,
          itemCount: _selectedAssets.length == 9 ? 9 : (_selectedAssets.length + 1),
          itemBuilder: (context, index) {
            return itemBuilder(_getChild(index: index), index);
          },
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: widget.lineCount,
            mainAxisSpacing: 10,
            crossAxisSpacing: 10,
          ),
        );
      },
    );
  }

  Widget _getChild({required int index}) {
    Key key = _selectedAssets.isEmpty || index >= _selectedAssets.length
        ? const Key('-100')
        : Key(_selectedAssets[index].toString());
    return CustomDraggable(
      key: key,
      data: index,
      child: SizedBox(
        // height: 100.0,
        // width: 100.0,
        child: index == _selectedAssets.length ? _addBtnWidget() : _itemWidget(index),
      ),
    );
  }

  void _handleReorder(ReorderedListFunction<AssetEntity> reorderedListFunction) {
    setState(() {
      _selectedAssets = reorderedListFunction(_selectedAssets);
    });
  }

  void _handleDragEnd(int index) {
    if (index == 0) {
      _showSnackbar(text: '这张照片将设置为封面');
    }
  }

  void _handleDragStarted(int index) {
    // _showSnackbar(text: 'Dragging at index $index has started!');
  }

  void _handleUpdatedDraggedChild(int index) {
    // _showSnackbar(text: 'Dragged child updated position to $index');
  }

  void _showSnackbar({required String text}) {
    // ScaffoldMessenger.of(context).clearSnackBars();
    // final snackBar = SnackBar(
    //   content: Text(
    //     text,
    //     style: const TextStyle(color: Colors.red),
    //   ),
    //   backgroundColor: Theme.of(context).colorScheme.surface,
    //   duration: const Duration(milliseconds: 1000),
    // );
    // ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  // 添加按钮
  Widget _addBtnWidget() {
    return GestureDetector(
      child: Container(
        // decoration: const BoxDecoration(color: Color(0xFFF4F6F6), borderRadius: BorderRadius.all(Radius.circular(6))),
        padding: const EdgeInsets.all(10.0),
        child: const Image(image: AssetImage('assets/app/images/world/post_publish_add.png')),
      ),
      onTap: () => showBottomSheet(),
    );
  }

  // 图片和删除按钮
  Widget _itemWidget(index) {
    return Container(
      color: Colors.transparent,
      child: Stack(
        alignment: Alignment.topRight,
        children: <Widget>[
          GestureDetector(
            onTap: () => _clickAsset(index),
            child: ConstrainedBox(
              constraints: const BoxConstraints.expand(),
              child: Container(child: _loadAsset(_selectedAssets[index])),
            ),
          ),
          GestureDetector(
            child: Container(
                padding: const EdgeInsets.all(3),
                // decoration: BoxDecoration(
                //     color: const Color(0xFF151313).withOpacity(0.47),
                //     borderRadius:
                //         const BorderRadius.only(topRight: Radius.circular(6), bottomLeft: Radius.circular(6))),
                child: Image.asset('assets/app/images/world/image_del_icon.png', width: 18)),
            onTap: () => _deleteAsset(index),
          )
        ],
      ),
    );
  }

  Widget _loadAsset(AssetEntity asset) {
    return Container(
        //超出部分，可裁剪
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(6)),
        child: Image(image: AssetEntityImageProvider(asset), fit: BoxFit.cover));
  }

  void _deleteAsset(index) {
    setState(() {
      _selectedAssets.removeAt(index);
      // 选择回调
      widget.callBack?.call(_selectedAssets);
    });
  }

  // 全屏查看
  void _clickAsset(index) {
    AssetPickerViewer.pushToViewer(
      context,
      currentIndex: index,
      previewAssets: _selectedAssets,
      themeData: AssetPicker.themeData(const Color(0xFF3BB815)),
    );
  }

  // 点击添加按钮
  void showBottomSheet() {
    AssetPickerSheet.showBottomSheet(
      maxAssets: widget.maxAssets,
      selected: _selectedAssets,
      callback: (assetEntityList) {
        widget.callBack?.call(assetEntityList);
        _selectedAssets = assetEntityList;
        setState(() {});
      },
    );
  }
}
